package com.cgwx.tmservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgwx.servicebase.exceptionhandler.MyException;
import com.cgwx.tmservice.entity.tm.TmParametersConfig;
import com.cgwx.tmservice.entity.vo.TmParamExcelVo;
import com.cgwx.tmservice.listener.TmParamExcelListener;
import com.cgwx.tmservice.mapper.TmParametersConfigMapper;
import com.cgwx.tmservice.service.TmParametersConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * <p>
 * 遥测参数配置表 服务实现类
 * </p>
 *
 * @author GaoWei
 * @since 2023-08-05
 */
@Service
public class TmParametersConfigServiceImpl extends ServiceImpl<TmParametersConfigMapper, TmParametersConfig> implements TmParametersConfigService {

//    更新遥测参数表配置
    @Override
    public void updateTmParametersConfig(MultipartFile file, TmParametersConfigService tmParametersConfigService) {
//        获取文件名称
        String uploadFileName = file.getOriginalFilename();
//        从文件名称中提取关键字，复波道_帧编号_帧类型码
        String uploadFileNameSubString = uploadFileName.substring(uploadFileName.indexOf("_") - 1);
        String tmframe_identifiers = uploadFileNameSubString.substring(0, uploadFileNameSubString.indexOf("."));

//        根据文件名检查是否存在同名遥测参数配置
        QueryWrapper<TmParametersConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tmframe_identifiers",tmframe_identifiers);
//        查询出的tmParam，可能为空
        Integer queryCount = baseMapper.selectCount(queryWrapper);

        if(queryCount != 0){
//            如果有，删除所有原来的配置
            baseMapper.delete(queryWrapper);
        }

//        读取Excel中的数据，插入到表中
        try {
//            文件输入流
            InputStream inputStream = file.getInputStream();
//            调用方法读取
            EasyExcel.read(inputStream, TmParamExcelVo.class, new TmParamExcelListener(tmParametersConfigService,tmframe_identifiers)).sheet().doRead();
        } catch (Exception e) {
            throw new MyException(20001,"读取遥测配置表格出错");
        }
    }
}
